package service

import (
	"beesoft.ink/application/garage/app/g"
	"beesoft.ink/application/garage/app/model"
	"github.com/labstack/echo/v4"
	"gorm.io/gorm/clause"
)

var Vehicle = vehicle{}

type vehicle struct{}

func (r vehicle) List(ctx echo.Context, req *model.VehicleListReq) []model.Vehicle {
	var items []model.Vehicle

	g.DB().
		Where("type", req.Type).
		Order(clause.OrderByColumn{
			Column: clause.Column{
				Name: req.Order,
			},
			Desc: req.OrderDirection,
		}).
		Offset((req.Page - 1) * req.PageSize).
		Limit(req.PageSize).
		Find(&items)

	return items
}
func (r vehicle) Show(ctx echo.Context) (*model.Vehicle, error) {
	id := ctx.Param("id")

	var item *model.Vehicle
	if err := g.DB().First(&item, id).Error; err != nil {
		return nil, err
	}

	return item, nil
}
func (r vehicle) Store(ctx echo.Context) error {
	item := new(model.Vehicle)

	if err := ctx.Bind(item); err != nil {
		return err
	}

	g.DB().Create(item)

	return nil
}
func (r vehicle) Update(ctx echo.Context) error {
	id := ctx.Param("id")

	var item *model.Vehicle
	if err := g.DB().First(&item, id).Error; err != nil {
		return err
	}

	if err := ctx.Bind(&item); err != nil {
		return err
	}

	g.DB().Save(&item)

	return nil
}
func (r vehicle) Destroy(ctx echo.Context, id uint) error {
	var item *model.Vehicle
	if err := g.DB().First(&item, id).Error; err != nil {
		return err
	}

	g.DB().Delete(&item)

	return nil
}
